import sys
import time
from PySide6.QtWidgets import QApplication, QMainWindow, QTextEdit
from PySide6.QtCore import QFileSystemWatcher
import itertools
import logging
import os


class FileWatcher(QMainWindow):
    line_number = 0
    file_size = 0

    def __init__(self, file_path):
        super().__init__()
        self.file_path = file_path

        self.text_edit = QTextEdit()
        self.setCentralWidget(self.text_edit)

        self.watcher = QFileSystemWatcher()
        self.watcher.fileChanged.connect(self.file_changed)
        self.watcher.addPath(self.file_path)

    def read_specific_lines(self):

        with open(file=self.file_path, mode="r", encoding="utf-8") as file:
            # 从起始行一直读到末尾
            return list(itertools.islice(file, self.line_number, None, None))

    def get_file_size(self, file_path):
        if os.path.isfile(file_path):
            # 获取文件大小（字节）
            file_size = os.path.getsize(file_path)
            return file_size
        else:
            return None

    def file_changed(self):
        print(self.file_path)
        sz = self.get_file_size(self.file_path)
        print(f"self.file_size:{self.file_size}")
        print(f"size:{sz}")
        if sz is not None and sz < self.file_size:
            self.line_number = 0
        lines = self.read_specific_lines()
        print(lines)
        self.line_number = self.line_number + len(lines)
        self.file_size=sz
        for line in lines:
            self.text_edit.append(line.strip())


if __name__ == "__main__":
    app = QApplication(sys.argv)
    file_path = "111.txt"  # 替换为要监控的文件路径
    window = FileWatcher(file_path)
    window.show()

    sys.exit(app.exec())
